package com.probiz.estoresa.system.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.common.model.system.SystemVersion;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.system.service.SystemVersionManager;


public class SystemVersionController extends GenericStoreAdminController<SystemVersion> {
    private SystemVersionManager mgr = null;

    public void setSystemVersionManager(SystemVersionManager inMgr) {
        this.mgr = inMgr;
    }
   
    public ModelAndView defaultAction(HttpServletRequest request, HttpServletResponse response)
    {
		SystemVersion sv = mgr.getSystemVersion();
		if (sv == null)
		{
			sv = new SystemVersion(); 
		}
		ModelAndView mv = new ModelAndView("systemVersionList","systemVersion", sv);
		return mv;
    	//return getRedirectToActionView("edit");
    }    
  	
    public ModelAndView save(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("entering 'onSubmit' method...");
		}

		SystemVersion systemVersion = formBackingObject(request);
		ServletRequestDataBinder binder = bindAndValidate(request, systemVersion);
		BindException errors = new BindException(binder.getBindingResult());
		

		boolean isNew = (systemVersion.getVersion() == null);

		License_ProBIZ_eStore li = new License_ProBIZ_eStore();
		String l_key = li.generate(systemVersion.getDomainName());
		if (!systemVersion.getLicenseKey().equals(l_key)) {
			ModelAndView mv = new ModelAndView("systemVersionList");
			errors.rejectValue("licenseKey", "license.illegal");
			mv.addAllObjects(errors.getModel());
			return mv;
		}
		// -----------------------------------------------------
		// do save operation - for SystemVersion
		// -----------------------------------------------------
		mgr.save(systemVersion);
		String key = (isNew) ? "systemVersion.added" : "systemVersion.updated";
		String message = getMessage(key, new Object[] { systemVersion.getId() });
		saveMessage(request, message);

		return this.getRedirectView("systemVersion.html");
//		return this.getRedirectToActionView("defaultAction");
	}

	protected SystemVersion formBackingObject(HttpServletRequest request) {
		String id = request.getParameter("id");
		SystemVersion systemVersion = null;

		if (!"".equals(request.getParameter("version"))
				&& !StringUtils.isEmpty(id)) {
			try {
				Integer pkey = new Integer(id);
				systemVersion = mgr.getById(pkey);
			} catch (Exception ex) {
				// Error retrieving value - so assume it is new
				logger.error(ex);
				systemVersion = new SystemVersion();
			}
		} else {
			systemVersion = new SystemVersion();
		}

		return systemVersion;
	}

	private class License_ProBIZ_eStore {
		private static final String PATTERN = "ProBIZ-2007-";

		private static final String L = "-- Copyright©2007 ProBIZ Software Technology Co., Ltd.";

		public String generate(String domain) {
			String pCode = "ProBIZ eStore" + L;
			String need = domain.substring(0, 1) + PATTERN;
			String dx = need + pCode + domain;
			int suf = decode(dx);
			return change(need + suf);
		}

		private int decode(String s) {
			int i = 0;
			char ac[] = s.toCharArray();
			int j = 0;
			for (int k = ac.length; j < k; j++) {
				i = 31 * i + ac[j];
			}
			return Math.abs(i);
		}

		private String change(String s) {
			byte abyte0[] = s.getBytes();
			char ac[] = new char[s.length()];
			int i = 0;
			for (int k = abyte0.length; i < k; i++) {
				int j = abyte0[i];
				if (j >= 48 && j <= 57)
					j = ((j - 48) + 5) % 10 + 48;
				else if (j >= 65 && j <= 90)
					j = ((j - 65) + 13) % 26 + 65;
				else if (j >= 97 && j <= 122)
					j = ((j - 97) + 13) % 26 + 97;
				ac[i] = (char) j;
			}
			return String.valueOf(ac);
		}
	}
    /*
     * (non-Javadoc)
     * 
     * @see com.probiz.estore.webapp.action.BaseListController#init()
     */
    public void init() {
    	
    }
	@Override
	protected String getEntityName(SystemVersion entity) {
		return null;
	}

	@Override
	protected void initController() throws Exception {
		
	}

	@Override
	protected void preSave(HttpServletRequest request, SystemVersion entity, BindException errors) {
		
	}
	
	public static void main(String[] args) {
		//测试;
		SystemVersionController controller = new SystemVersionController();
		License_ProBIZ_eStore eStore =  controller.new License_ProBIZ_eStore();
		String l_key = eStore.generate("localhost");
		System.out.println(l_key); 
	}
}
